<?php
//ham dieu khien
	function a_display(){
		//dump($tb);
		global $task;
		switch($task){
			case 'status':
				status(Request::get("make","confirm"));
				break;
			case 'remove':
				remove();
				break;
			default:
				viewDefault();
				break;
		}
	}
	
	function viewDefault(){
		require_once('base/class.pagination.php');
		$search = Request::get('search');
		$status = Request::get('status');
		
		$total = getCountProduct($search,$status);
		$lms = Request::get('limitstart',0);
		$lm = Request::get('limit',10);
		$pageNav = new Pagination($total,$lms,$lm);
		$products = getAllProduct($search,$status);
		
		
		?>
		<table class="toolbar-fitter" border="0" width="100%" cellpadding="0" cellspacing="0" id="product-table">
			<tr>
				<td width="100%"><input type="text" name="search" value="<?php echo $search;?>" /><input class="search" type="submit" value="Search" /></td>
				<td nowrap="nowrap">
					<select name="status">
						<option value="">--Select status--</option>
						<option value="1">Done</option>
						<option value="0">Waiting</option>
					</select>
				</td>
				<td><input class="next" type="submit" name="search-fitter" value="Xem" /></td>
			</tr>
		</table>
		
		<table class="adminlist">
			<thead>
			<tr>
				<th width="10"><a href="">STT</a></th>
                <th width="10" ><input type="checkbox" value="on" name="allbox" onclick="checkAll();"/></th>
                <th nowrap="nowrap">Order Name</th>
                <th nowrap="nowrap">Order Phone</th>
                <th nowrap="nowrap">Status</th>
                <th nowrap="nowrap">Created</th>
                
                <th nowrap="nowrap">Order Product</th>
                <th nowrap="nowrap">Quanlity</th>
                <th nowrap="nowrap">Price</th>
                <th nowrap="nowrap">Total</th>
			</tr>
			</thead>
			<?php 
			$i = 1; foreach($products AS $groupProduct) {
			$j = 0;
			$count = count($groupProduct);
			if(count($groupProduct)>0)foreach ($groupProduct as $product){
				$orderId 			 = $product['id'];
				$orderCreated 		 = $product['created'];
				$orderStatus 		 = ($product['status'] == 0) ? '<a href="index.php?option=order&task=status&make=confirm&id='.$orderId.'" title="Confirm this order">Waiting</a>' 
																  : '<a href="index.php?option=order&task=status&make=unconfirm&id='.$orderId.'" title="Unconfirm this order">Done</a>';
				$orderName 		 	 = $product['order_name'];
				$orderPhone 	 	 = $product['order_phone'];
				$orderProduct    	 = $product['title'];
				$orderQuantity   	 = $product['quantity'];
				$orderPrice      	 = $product['price'];
				$orderPrice      	 = number_format($orderPrice,0,'.','.').' VND';
										//.getProductAttribute('product_currency','code',$product['product_currency_id']);
				$orderTotalPrice 	 = $product['quantity'] * $product['price'];
										//.getProductAttribute('product_currency','code',$product['product_currency_id'])
				$orderTotalPrice 	 = number_format($orderTotalPrice,0,'.','.').' VND';
				?>
				<tr>
					<?php if($j ==0){ ?>
					<td rowspan="<?php echo $count?>"><?php echo $pageNav->getOfset($i);?></td>
					<td rowspan="<?php echo $count?>"><input id="actions-box" name="id[]" value="<?php echo $orderId;?>"  type="checkbox"/></td>
					<td rowspan="<?php echo $count?>"><a href=""><?php echo $orderName;?></a></td>
					<td rowspan="<?php echo $count?>"><a href=""><?php echo $orderPhone;?></a></td>
					<td rowspan="<?php echo $count?>"><a href=""><?php echo $orderStatus;?></a></td>
					<td rowspan="<?php echo $count?>"><a href=""><?php echo $orderCreated;?></a></td>
					
					<?php  $j=$j+1;} ?>
					<td><a href=""><?php echo $orderProduct;?></a></td>
					<td><a href=""><?php echo $orderQuantity;?></a></td>
					<td><a href=""><?php echo $orderPrice;?></a></td>
					<td><a href=""><?php echo $orderTotalPrice;?></a></td>
				</tr>
			<?php $i++; }
			}?>
			<tr>
				<td style="border:none !important;" colspan="13"><?php $pageNav->displayCpanel();?></td>
			</tr>
		</table>
		<?php
		
		echo '<input type="hidden" name="option" value="order" />';
		
	}
	
	
	function cancel(){
		$option = Request::get('option');
		header('Location:index.php?option='.$option);
	}
	function remove(){
		global $dbo;
		$id = Request::get('id');
		$query1 = " SELECT id FROM order_detail WHERE invoice_id IN(".implode(',',$id).") ";
		$dbo->setQuery($query1);
		$listOrderDetail = $dbo->loadColums();
		
		echo $query = " DELETE FROM `invoice` WHERE WHERE id IN(".implode(',',$id).") ";
		$dbo->setQuery($query);
		$dbo->query();
		
		echo $query = " DELETE FROM `order_detail` WHERE WHERE invoice_id IN(".implode(',',$listOrderDetail).") ";
		$dbo->setQuery($query);
		$dbo->query();
		
		viewDefault();
		Message::setMessage($num.' Item(s) permanently deleted');
		redirect('index.php?option=order');
	}
	function status($task){
		//lay danh sach cac record can thay doi trang thai published
		$id = Request::get('id');
		if(gettype($id)=="string") $id=array($id);
		$p = ($task == 'confirm')? 1:0;
		$query = " UPDATE `invoice` SET `status` = ".$p." WHERE id IN(".implode(',',$id).") ";
		global $dbo;
		$dbo->setQuery($query);
		$dbo->query();
		viewDefault();
	}
    
	
	
	function getAllProduct($s='',$status=''){	//lay tat cac cac user de hien thi ra luoi du lieu
		global $dbo;
		$lms = Request::get('limitstart',0);
		$lm = Request::get('limit',10);
		$query = "SELECT od.quantity,od.created,    p.title,p.price,p.product_currency_id,   i.id,i.order_name,i.order_phone,i.status
				  FROM order_detail as od,  invoice as i, products as p
				  WHERE     od.invoice_id = i.id
				  		AND od.product_id = p.id";
		
		if ($s) $query .= " AND (i.order_name LIKE '%$s%') ";
		switch ($status){
			case '1': $query .= " AND i.status = '1' ";
				break;
			case '0': $query .= " AND i.status = '0' ";
				break;
		}
		$query .= " ORDER BY id ASC ";
        $query .= " LIMIT $lms,$lm";
        $dbo->setQuery($query);
        $tmp= $dbo->loadResultArray();
        /*
         * list of id (invoice)
         */
        $subQuerry = "SELECT id FROM invoice";
        $dbo->setQuery($subQuerry);
        $invoiceIdList = $dbo->loadColums();
        foreach ($invoiceIdList as $id){
        	for($i=0;$i<count($tmp);$i++){
        		if($tmp[$i]["id"] == $id) {
        			$tmpRsult[] = $tmp[$i];
//         			unset($tmp[$i]);
        		}
        	}
        	$finalResult[$id] = $tmpRsult;
        	$tmpRsult = array();
        }
       
		return $finalResult;
		
	}
	
	function getCountProduct($s='',$status=''){
		global $dbo;
		$query = "SELECT COUNT(i.id)
								FROM invoice as i
					";
		if ($s !='') $where[] = " (i.order_name LIKE '%$s%') ";
		switch ($status){
			case '1': $where[]= " i.status = '1' ";
				break;
			case '0': $where[]= " i.status = '0' ";
				break;
		}
		if(count($where)>0) $whereClause = " WHERE ".implode(" AND ",$where);
		$query .= $whereClause;
		
		$dbo->setQuery($query);
		
		return $dbo->loadResult();
	}
	
	
/********************Functions for viewDefault*********************/
	//ham lay ve danh sach cac attribute cua san pham nhu : section, categories... de loc
	function getFilterAttribute($filtername){
		global $dbo;
		$dbo->setQuery("SELECT title,id FROM $filtername ");
		$attributes = $dbo->loadObjectList();
			foreach ($attributes as $attribute){
				echo '<option name="" value="'.$attribute->id.'" >'.$attribute->title.'</option>';
			}
			echo $attribute->title;
	}
	
	
	
	function getProductAttribute($table,$properties,$id){
		global $dbo;
		$dbo->setQuery("SELECT $properties FROM $table WHERE id = $id ");
		$results =  $dbo->loadObjectList();
		foreach ($results AS $result){
			return $result->$properties;
		}
	}
	
	
	
	
	
	
	
/********************Functions for viewAdd*********************/
	//Ham lay ve ten 	Created by  va Modified by
	function getUser($uid){
		global $dbo;
		$dbo->setQuery("SELECT username FROM users WHERE id =$uid ");
		$user =  $dbo->loadObjectList();
		foreach ($user AS $u){
			return $u->username;
		}
	}
	
	function selectAccessGroup($gid=null){
		global $dbo;
		$dbo->setQuery("SELECT name,id
						FROM groups
						");
		$groups = $dbo->loadObjectList();
		echo '<select name="access" style="width:140px;">';
		echo '<option selected="selected" value="0" >Public</option>';
		foreach ($groups AS $g){ ?>
			<option value="<?php echo $g->id; ?>" <?php if ($g->id == $gid) echo 'selected = "selected"'; ?>> <?php echo $g->name; ?></option>
		<?php  }
		echo '</select>';
	}
	
	function selectProductDiscount($discount_id=''){
		global $dbo;
		$dbo->setQuery("SELECT id,percent,description
						FROM product_discount ORDER BY id ASC ");
		$discounts = $dbo->loadObjectList();
		echo '<select name="product_discount_id">';
		foreach ($discounts AS $discount){ ?>
			<option <?php if($discount->id == $discount_id) echo 'selected="selected"'?> value="<?php echo $discount->id; ?>"><?php echo '('.$discount->percent.'%) '.$discount->description; ?></option>
		<?php }
		echo '</select>';
	}
	
	//ham lay ve nhieu thuoc tinh khac cua san pham
	function selectProductAttribute($table,$properties,$name,$id=''){
		global $dbo;
		$dbo->setQuery("SELECT id,".$properties." FROM ".$table." ORDER BY id ASC");
		$results = $dbo->loadObjectList();
		echo '<select name="'.$name.'">';
		foreach ($results AS $result){ ?>
			<option value="<?php echo $result->id; ?>" <?php if ($result->id == $id) echo 'selected = "selected"'; ?>> <?php echo $result->$properties; ?></option>
		<?php  }
		echo '</select>';
	}
	
	
	//select ngon ngu ho tro cho dien thoai
	
	
		function selectProductLanguage($pro_id='', $lang_id=''){
		global $dbo;
		
		$dbo->setQuery("SELECT id,title
						FROM products
						INNER JOIN product_language
						INNER JOIN rs_product_language
						ON products.id = rs_product_language.product_id AND rs_product_language.language_id = product_language.id
						ORDER BY product_language.id ASC ");
						
		
		
		$results = $dbo->loadObjectList();
		echo '<select name="product_discount_id" multiple="multiple">';
		foreach ($results AS $result){ ?>
			<option <?php if($result->products.id == $pro_id && $result->product_language.id == $lang_id) echo 'selected="selected"'?> value="<?php echo $result->product_id; ?>"><?php echo $result->langtitle; ?></option>
			
		<?php }
		echo '</select>';
		
		
	}
	
	
	
	/*
	function selectProductLanguage($pro_id='', $lang_id=''){
		global $dbo;
		
		$dbo->setQuery("SELECT products.id,products.title,product_language.id,product_id,language_id,product_language.title AS langtitle
						FROM products
						INNER JOIN product_language
						INNER JOIN rs_product_language
						ON products.id = rs_product_language.product_id AND rs_product_language.language_id = product_language.id
						ORDER BY product_language.id ASC ");
						
		
		
		$results = $dbo->loadObjectList();
		echo '<select name="product_discount_id" multiple="multiple">';
		foreach ($results AS $result){ ?>
			<option <?php if($result->products.id == $pro_id && $result->product_language.id == $lang_id) echo 'selected="selected"'?> value="<?php echo $result->product_id; ?>"><?php echo $result->langtitle; ?></option>
			
		<?php }
		echo '</select>';
		
		
	}
	
	*/
	
		
	

?>
